const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const GRID_SIZE = 20;
const GRID_COUNT = canvas.width / GRID_SIZE;

let snake = [
  { x: 10, y: 10 }
];
let food = generateFood();
let dx = 1;
let dy = 0;
let score = 0;
let gameLoop;

function generateFood() {
  let position;
  do {
    position = {
      x: Math.floor(Math.random() * GRID_COUNT),
      y: Math.floor(Math.random() * GRID_COUNT)
    };
  } while (snake.some(segment => segment.x === position.x && segment.y === position.y));
  return position;
}

function drawGame() {
  // 移动蛇身
  const head = { x: snake[0].x + dx, y: snake[0].y + dy };
  snake.unshift(head);

  // 碰撞检测
  if (head.x === food.x && head.y === food.y) {
    score += 10;
    document.getElementById('score').textContent = score;
    food = generateFood();
  } else {
    snake.pop();
  }

  // 游戏结束条件
  if (head.x < 0 || head.x >= GRID_COUNT || head.y < 0 || head.y >= GRID_COUNT ||
      snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)) {
    gameOver();
    return;
  }

  // 清空画布
  ctx.fillStyle = '#34495e';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 绘制食物
  ctx.fillStyle = '#e74c3c';
  ctx.fillRect(food.x * GRID_SIZE, food.y * GRID_SIZE, GRID_SIZE - 2, GRID_SIZE - 2);

  // 绘制蛇身
  snake.forEach((segment, index) => {
    ctx.fillStyle = index === 0 ? '#2ecc71' : '#27ae60';
    ctx.fillRect(segment.x * GRID_SIZE, segment.y * GRID_SIZE, GRID_SIZE - 2, GRID_SIZE - 2);
  });
}

function gameOver() {
  clearInterval(gameLoop);
  alert(`游戏结束！得分：${score}`);
}

// 键盘控制
document.addEventListener('keydown', (e) => {
  switch (e.key) {
    case 'ArrowUp':
      if (dy !== 1) { dx = 0; dy = -1; }
      break;
    case 'ArrowDown':
      if (dy !== -1) { dx = 0; dy = 1; }
      break;
    case 'ArrowLeft':
      if (dx !== 1) { dx = -1; dy = 0; }
      break;
    case 'ArrowRight':
      if (dx !== -1) { dx = 1; dy = 0; }
      break;
  }
});

// 重新开始游戏
document.getElementById('restartBtn').addEventListener('click', () => {
  snake = [{ x: 10, y: 10 }];
  food = generateFood();
  dx = 1;
  dy = 0;
  score = 0;
  document.getElementById('score').textContent = score;
  clearInterval(gameLoop);
  gameLoop = setInterval(drawGame, 100);
});

// 启动游戏
gameLoop = setInterval(drawGame, 100);